<template>
  <van-icon
    :name="value ? 'star' : 'star-o'"
    :color="value ? ' #ffa500' : ''"
    @click="collectBtn"
    :loading="loading"
  ></van-icon>
</template>

<script>
import { collectArticles, cancelCollectArticles } from '@/api/article.js'
export default {
  name: 'collectArticle',
  data() {
    return {
      loading: false
    }
  },
  props: {
    value: {
      type: Boolean,
      required: true
    },
    articleId: {
      type: [String, Number, Object],
      required: true
    }
  },
  methods: {
    // 收藏按钮
    async collectBtn() {
      this.loading = true
      try {
        if (this.value) {
          // 已收藏 取消收藏
          await cancelCollectArticles(this.articleId)
          this.$toast.success('取消收藏')
        } else {
          // 未收藏 添加收藏
          await collectArticles(this.articleId)
          this.$toast.success('收藏成功')
        }
        // 更新视图 不能直接修改传过来的值
        this.$emit('input', !this.value)
      } catch (err) {
        this.$toast.fail('操作失败，请重试')
      }
      this.loading = false
    }
  }
}
</script>

<style scoped lang="less"></style>
